package com.supor.md_video.ui;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.ViewModelProvider;

import com.android.baseconfig.base.BaseApiResult;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.utils.ToastUtils;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseDialogFragment;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.md_video.R;
import com.supor.md_video.api.VideoApiImpl;
import com.supor.md_video.databinding.DialogVideoCommInputBinding;
import com.supor.md_video.entity.VideoCommListBean;
import com.supor.md_video.model.VideoListModel;

import java.text.SimpleDateFormat;
import java.util.Date;

import autodispose2.AutoDispose;
import autodispose2.AutoDisposeConverter;
import autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class CommInputDialog extends BaseDialogFragment<DialogVideoCommInputBinding> {

    private int mAllowableErrorHeight;
    //    private VideoListModel videoCommModel;
    private String addId;
    private int videoPosition;
    private String recipeId;

    public static CommInputDialog newInstance(String addrId, String recipeId, int videoPosition) {
        CommInputDialog fragment = new CommInputDialog();
        Bundle bundle = new Bundle();
        bundle.putString("ADDR_ID", addrId);
        bundle.putString("RECIPE_ID", recipeId);
        bundle.putInt("VIDEO_POSITION", videoPosition);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (null != getArguments()) {
            addId = getArguments().getString("ADDR_ID");
            recipeId = getArguments().getString("RECIPE_ID");
            videoPosition = getArguments().getInt("VIDEO_POSITION");
        }
//        <item name="android:windowSoftInputMode">stateAlwaysVisible</item><!--显示软件盘-->
        setStyle(R.style.CommInputDialogStyle);
    }

    @Override
    protected void initView() {
        binding.etContent.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    if (!TextUtils.isEmpty(binding.etContent.getText().toString().trim())) {
//                        videoCommModel.sendComm(binding.etContent.getText().toString().trim(), addId,
//                                recipeId,
//                                videoPosition, bindDestoryAutoDispose());
                        sendComm(binding.etContent.getText().toString().trim(), addId,
                                recipeId,
                                videoPosition, bindDestoryAutoDispose());
                    }
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    protected void initEvents() {
//        videoCommModel = new ViewModelProvider(getActivity(),
//                ViewModelProvider.AndroidViewModelFactory.getInstance(AppAgent.getApp())).get(VideoListModel.class);
//        videoCommModel.getVideoCommAddResult()
//                .observe(this, result -> {
//                    if (null != result.getData()) {
//                        RxBus3.getInstance().post(Constants.TicPecipe.COMM_ADD, result.getData());
//                    } else {
//                        ToastUtils.getInstance().showToast(getActivity(), "添加评论失败请稍后重试～");
//                    }
//                    dismiss();
//                });
    }

    @Override
    protected void initNotify() {

    }

    @Override
    public void widgetClick(View v) {

    }

    @Override
    public void onResume() {
        super.onResume();
        showSoftInputFromWindow();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding.etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String content = binding.etContent.getText().toString();
//                if(mOnDisMissCallBack != null){
//                    mOnDisMissCallBack.onCommendTextChanged(content);
//                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //设置已经填过的文字，以及移动光标
//        binding.etContent.setText(mContent);
//        if(!TextUtils.isEmpty(mContent) && mContent.length() > 0){
//            mBinding.mEditText.setSelection(mContent.length());
//        }
//        showSoftInputFromWindow();
    }

    public void showSoftInputFromWindow() {
        binding.etContent.postDelayed(new Runnable() {
            @Override
            public void run() {
                binding.etContent.setFocusable(true);
                binding.etContent.setFocusableInTouchMode(true);
                binding.etContent.requestFocus();
                if (null != getActivity()) {

                    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (null != imm) {
                        imm.showSoftInput(binding.etContent, 0);
                    }
                }
            }
        }, 100);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        Window window = getDialog().getWindow();
        super.onActivityCreated(savedInstanceState);


        getDialog().setCancelable(true);
        getDialog().setCanceledOnTouchOutside(true);
        //设置背景为透明
        window.setWindowAnimations(R.style.AnimBottom);
        window.setBackgroundDrawable(ContextCompat.getDrawable(getContext(), android.R.color.transparent));
        //去除阴影
        window.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        layoutParams.dimAmount = 0.5f;
        window.setAttributes(layoutParams);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
//        getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
//            @Override
//            public void onDismiss(DialogInterface dialog) {
//                dismissDialog();
//            }
//        });

    }

    public <T> AutoDisposeConverter<T> bindDestoryAutoDispose() {
        return AutoDispose.autoDisposable(
                AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)
        );
    }

    public void sendComm(String text, String addrId, String recipeId, int position,
                         AutoDisposeConverter<BaseApiResult<VideoCommListBean>> autoDisposeConverter) {
        if (null == GlobalDataCache.userInfo || !AppAgent.isLogin()) {
            ToastUtils.getInstance().showToast(getActivity(), "请先登录");
            return;
        }
        VideoApiImpl.getInstance().commFilter(text)
                .filter(result -> result.isSuccess())
                .flatMap((Function<BaseApiResult<String>, ObservableSource<BaseApiResult<VideoCommListBean>>>) result -> {
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String currentTime = sdf.format(date);
                    return VideoApiImpl.getInstance().addComm(text,
                            GlobalDataCache.userInfo.getBossUserId(),
                            addrId, recipeId, text, currentTime
                    ).subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread());
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .to(autoDisposeConverter)
                .subscribe(new Consumer<BaseApiResult<VideoCommListBean>>() {
                               @Override
                               public void accept(BaseApiResult<VideoCommListBean> videoCommListBeanBaseApiResult) throws Exception {
                                   videoCommListBeanBaseApiResult.data.setIsMyself(1);
                                   videoCommListBeanBaseApiResult.data.setHeadPortaint(GlobalDataCache.userInfo.getFaceImage());
                                   videoCommListBeanBaseApiResult.data.setNickName(GlobalDataCache.userInfo.getNickName());
                                   videoCommListBeanBaseApiResult.data.setLocalId(addrId);
                                   videoCommListBeanBaseApiResult.data.setLocalPosition(position);
//                                   videoCommAddResult.setValue(new Result.Success<>(videoCommListBeanBaseApiResult.data));
                                   if (null != videoCommListBeanBaseApiResult.data) {
                                       RxBus3.getInstance().post(Constants.TicPecipe.COMM_ADD, videoCommListBeanBaseApiResult.data);
                                   } else {
                                       ToastUtils.getInstance().showToast(getActivity(), "添加评论失败请稍后重试～");
                                   }
                                   dismiss();
                               }
                           },
                        throwable -> ToastUtils.getInstance().showToast(getActivity(), "添加评论失败请稍后重试～"));

    }
}
